<?php
class SubfolderAccessManager_Util_Directory {

    public function getRootDirectory() {
        $config = Zend_Registry::get('config');
        return $config->subfolder->root->dir;
    }

    public function getMasterPath()
    {
        return @file_get_contents('resources/root_folder.dat');;
    }

    public function setMasterPath($rootFolder)
    {
        return @file_put_contents('resources/root_folder.dat', $rootFolder);
    }

    public function getFolderExceptions()
    {
        $folderExceptions = file('resources/folder_exceptions.dat', FILE_IGNORE_NEW_LINES);

        return $folderExceptions;
    }

    public function hasAccessToSubfolder($directory)
    {
        $hasAccess = true;
        $accessFile = $directory . '/.htaccess';
        if (file_exists($accessFile)) {
            $fileContents = file_get_contents($accessFile);
            if (strpos($fileContents, 'ADMIN_RESTRICTION')) {
                $hasAccess = false;
            }
        }
        return $hasAccess;
    }

    public function disableAccessToSubfolder($rootDir, $subfolderName)
    {
        $htAccess = $rootDir . $subfolderName . '/.htaccess';
        $originalHtAccessContent = @file_get_contents($htAccess);
        $htAccessFile = fopen($htAccess, 'w+');
        $htAccessRestrictions = file_get_contents('resources/htaccess.dat');
        fwrite($htAccessFile, $htAccessRestrictions . $originalHtAccessContent);
        fclose($htAccessFile);
    }

    public function enableAccessToSubfolder($rootDir, $subfolderName)
    {
        $htAccess = $rootDir . $subfolderName . '/.htaccess';
        if (file_exists($htAccess)) {
            $originalHtAccessContent = @file_get_contents($htAccess);
            $htAccessFile= fopen($htAccess,'w');
            $htAccessRestrictions = file_get_contents('resources/htaccess.dat');
            $htAccessNoRestrictions = str_replace($htAccessRestrictions, '', $originalHtAccessContent);
            fwrite($htAccessFile,$htAccessNoRestrictions);
            fclose($htAccessFile);
        }
    }
}